package net.ezsteam.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.ezsteam.EzSteam_StoreVisit_Activity;
import net.ezsteam.R;
import net.ezsteam.cons.EzSteam_Urls;
import net.ezsteam.object.EzSteam_Checked_Car;
import net.ezsteam.service.EzSteam_Appoinment_Service.MyAdapter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;


public class EzSteam_GetRecalled_Cars extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	ListView listview;

	private MyAdapter myAdapter;
	
	private boolean exeption = false;
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;

	JSONArray jArray;
	
	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = ""; 
	List<NameValuePair> params;
	
	HttpParams httpParameters = new BasicHttpParams();
	
	String[] arrAllCars;
	String[] arrPassIDs;
	String[] arrCarID;
	String[] arrTypeID;

	
	public EzSteam_GetRecalled_Cars(Activity activity,String[] allCar,String[] allIDs,ListView listview) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.arrAllCars = new String[allCar.length];
		this.arrAllCars = allCar;
		this.arrPassIDs = new String[allIDs.length];
		this.arrPassIDs = allIDs;
		this.listview = listview;
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Recalled Cars", "Recalling cars, Please Wait",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {

		try {
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(urls[0]));
		    
			HttpEntity httpEntity = response.getEntity();

			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				exeption = true;
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IOException e) {   
				exeption = true;
				e.printStackTrace();
			} catch (IllegalStateException e) {
				exeption = true;
				e.printStackTrace();
			} catch (Exception e) {
				exeption = true;
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				exeption = true;
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
		 return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		Log.d("Post Exec", "POST EXEC");
		
		Log.d("recall Apponiment", result);
		progdialod.dismiss();

		
		Log.d("Post Exec", result); //"result" is the token *if not null
		
		Log.i("All Cars Length", ""+arrAllCars.length);
		
		
			if(!exeption){
				
				try {

					JSONObject jsonobj = new JSONObject(result);
					JSONArray service_type = jsonobj.getJSONArray("car_details");

					arrCarID = new String[service_type.length()];
					arrTypeID = new String[service_type.length()];

					for(int typei=0;typei<service_type.length();typei++){
						if(service_type.get(typei) instanceof JSONObject){
							JSONObject jsonDetails = service_type.getJSONObject(typei);
							arrCarID[typei] = jsonDetails.getString("car_id");
							arrTypeID[typei] = jsonDetails.getString("clean_type_id");
							
							Log.i("arrCarID[typei]", arrCarID[typei]);
							
						}
					}

					
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				
				
				
			
			}else{
				Toast toast = Toast.makeText(activity, "Failed !!", Toast.LENGTH_SHORT);
				toast.show();
			}
			
			if(arrAllCars.length != 0){

			    myAdapter = new MyAdapter();

		        listview.setAdapter(myAdapter);
		        //listview.setAdapter(mAdapter2);
			}

	}
	
	public class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MyAdapter() {
            mInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            
            
        }

        public int getCount() {
            return arrAllCars.length;
        }

        public String getItem(int position) {
            return arrAllCars[position];
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            
            
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.ezsteam_cleanlist_row, null);
                holder.txt_title = (TextView)convertView.findViewById(R.id.txt_title);
                holder.chk_car=(CheckBox)convertView.findViewById(R.id.chk_car); 
                
                //GET ALL CheckBox Features Inside fist convert view only
                
                if(arrCarID!=null){
                	
	                if(arrCarID.length != 0){
	
	                	if (Arrays.asList(arrCarID).contains(arrPassIDs[position])) {
	                		holder.chk_car.setChecked(true);
	                    }
					    
	                }
                }
                
                
                holder.spn_cleantype = (Spinner) convertView.findViewById(R.id.spn_cleantype);

                if(holder.spn_cleantype.getChildCount()==0){
                
                	if(arrCarID!=null){
		                EzSteam_Clean_Type sstype = new EzSteam_Clean_Type(activity,holder.spn_cleantype,arrTypeID,arrCarID,arrPassIDs,arrPassIDs[position]);
		                sstype.execute(EzSteam_Urls.GET_Clean_Types);
                	}else{
                		EzSteam_Clean_Type sstype = new EzSteam_Clean_Type(activity,holder.spn_cleantype,arrPassIDs);
    	                sstype.execute(EzSteam_Urls.GET_Clean_Types);
                	}
	                
                }
                
                final int actpos = position;
                
                holder.spn_cleantype.setOnItemSelectedListener(new OnItemSelectedListener() {
    			    @Override
    			    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
    			    	 if(holder.chk_car.isChecked()){
    			    		Log.e("CARID", arrPassIDs[actpos]);
    						Log.e("CLEANTYPE", holder.spn_cleantype.getSelectedItem().toString());
    						
    						boolean contains = false;
    						EzSteam_Checked_Car obj = new EzSteam_Checked_Car("","");
    						
    						for(int inc=0;inc<EzSteam_StoreVisit_Activity.cars.size();inc++){
    							Log.i("CarID Checked", EzSteam_StoreVisit_Activity.cars.get(inc).getCarID());
    							if(arrPassIDs[actpos].equals(EzSteam_StoreVisit_Activity.cars.get(inc).getCarID())){
    								contains=true;
    								obj = EzSteam_StoreVisit_Activity.cars.get(inc);
    							}
    						}
    						
    						if(contains){
    							
    							EzSteam_StoreVisit_Activity.cars.remove(obj);
    							
    							EzSteam_StoreVisit_Activity.cars.add(new EzSteam_Checked_Car(arrPassIDs[actpos],  ""+holder.spn_cleantype.getSelectedItem().toString().split(":")[0]));
    						}
    						
    					}
    			    }

    			    @Override
    			    public void onNothingSelected(AdapterView<?> parentView) {
    			    	
    			    }

    			});
                
                holder.chk_car.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    				
    				@Override
    				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    					if(isChecked){
    						Log.e("CARID", arrPassIDs[position]);
    						Log.e("CLEANTYPE", holder.spn_cleantype.getSelectedItem().toString());
    						
    						boolean contains = false;
    						
    						for(int inc=0;inc<EzSteam_StoreVisit_Activity.cars.size();inc++){
    							Log.i("CarID Checked", EzSteam_StoreVisit_Activity.cars.get(inc).getCarID());
    							if(arrPassIDs[position].equals(EzSteam_StoreVisit_Activity.cars.get(inc).getCarID())){
    								contains=true;
    							}
    						}
    						
    						if(!contains){
    							//EzSteam_StoreVisit_Activity.cars.add(new EzSteam_Checked_Car(arrCarID[position],  holder.spn_cleantype.getSelectedItem().toString()));
    							EzSteam_StoreVisit_Activity.cars.add(new EzSteam_Checked_Car(arrPassIDs[position],  ""+holder.spn_cleantype.getSelectedItem().toString().split(":")[0]));
    						}
    						
    					}else{
    						Log.e("CARID not Checked", arrPassIDs[position]);
    						Log.e("CLEANTYPE not Checked", holder.spn_cleantype.getSelectedItem().toString());
    						//Log.e("CONTAINS not Checked", ""+EzSteam_StoreVisit_Activity.cars.contains(new EzSteam_Checked_Car(arrCarID[position],  holder.spn_cleantype.getSelectedItem().toString())));
    						
    						boolean contains = false;
    						EzSteam_Checked_Car obj = new EzSteam_Checked_Car("","");
    						
    						for(int inc=0;inc<EzSteam_StoreVisit_Activity.cars.size();inc++){
    							Log.i("CarID not Checked", EzSteam_StoreVisit_Activity.cars.get(inc).getCarID());
    							if(arrPassIDs[position].equals(EzSteam_StoreVisit_Activity.cars.get(inc).getCarID())){
    								contains=true;
    								obj = EzSteam_StoreVisit_Activity.cars.get(inc);
    							}
    						}
    						
    						if(contains){
    							Log.e("About To Remove", "About To Remove");
    							EzSteam_StoreVisit_Activity.cars.remove(obj);
    						}
    					}
    				}
    			});

                
                
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            
            
            holder.txt_title.setTag(position);
            holder.chk_car.setText(arrAllCars[position]);

            return convertView;
        }

    }

    class ViewHolder {

    	TextView txt_title;
    	CheckBox chk_car;
    	Spinner spn_cleantype;
    }

}
